<template>
  <div class="energy-electricity-electriccharge">
    <!-- 下拉列表 -->
    <el-card class="content__left">
      <realtimemonito-menu :data="menus" v-model:menu-id="menuId" v-model:open-id="openId" @menu-click="commEvent.menuClick" />
    </el-card>
    <!-- 展示信息 -->
    <div class="content__right">
      <el-card>
        <div class="card__title">能碳系统演示-电荷分析</div>
        <!-- 搜索 -->
        <el-row :gutter="20" align="middle" class="mt10">
          <el-col :span="4">
            <el-segmented v-model="dateRange" :options="dateOption" @change="commEvent.onDateRange" />
          </el-col>
          <el-col :span="8">
            <div class="right-search">
              <div class="search__label">时间：</div>
              <div class="search__value">
                <el-date-picker v-model="searchValue.dataTime" :type="dataTimeType" placeholder="请选择" style="width: 100%" />
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="right-search">
              <div class="search__label">生产设备：</div>
              <div class="search__value">
                <el-select v-model="searchValue.deviceId" filterable>
                  <el-option v-for="item in devices" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div style="display: flex; justify-content: flex-end; gap: 10px">
              <el-button type="primary" icon="Search" @click="commEvent.getStatData">搜索</el-button>
              <el-button icon="Refresh" @click="commEvent.onReset">重置</el-button>
            </div>
          </el-col>
        </el-row>
        <!-- 图表 -->
        <div v-if="chargeAnalysises.length" class="right-chart mt20">
          <e-charts :option="chargeAnalysisOption" />
        </div>
        <el-empty v-else />
        <el-descriptions :column="2" border class="mt20">
          <el-descriptions-item label="平均负荷">{{ desctrtionValue.avgLoad }}</el-descriptions-item>
          <el-descriptions-item label="负荷率">{{ desctrtionValue.loadRate }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue"
import RealtimemonitoMenu, { MenuType } from "../components/RealtimemonitoMenu.vue"
import ECharts from "@/components/ECharts/index.vue"
import { ECOption } from "@/components/ECharts/config"
import { dateOption, chargeAnalysisChart, dateValue } from "./enum"
import dayjs from "dayjs"
import { organTree } from "@/api/modules/system"
import { SystemSpace as SystemApi } from "@/api/interface/system"
import { deviceListEnergy } from "@/api/modules/archive"
import { SystemSpace as SystemArchive } from "@/api/interface/archive"
import { electricStat } from "@/api/modules/energy"
import { SystemSpace } from "@/api/interface/energy"
// 参数
const menus = ref<MenuType[]>([]) // 菜单树结构
const openId = ref<number[]>([]) // 展开id
const menuId = ref<number>(-1) //菜单选中id
const dateRange = ref<string>("hour") // 期间
const devices = ref<SystemArchive.DeviceListEnergy[]>([]) // 设备列表
const desctrtionValue = ref({
  avgLoad: 0,
  loadRate: "0.00%"
})
// 时间类型
const dataTimeType = computed<"date" | "month" | "year">(() => {
  const _enum: any = {
    hour: "date",
    day: "month",
    month: "year"
  }
  return _enum[dateRange.value]
})
// 搜索项
const searchValue = ref({
  factoryId: undefined as undefined | number,
  lineId: undefined as undefined | number,
  dataTime: dayjs().format("YYYY-MM-DD"),
  deviceId: undefined as undefined | number,
  energyType: "electric"
})
// 电荷分析
const chargeAnalysises = ref<SystemSpace.ElectricStat["loadList"]>([])
const chargeAnalysisOption = computed<ECOption>(() => {
  let _series: any = {}
  if (chargeAnalysisChart?.series && Array.isArray(chargeAnalysisChart.series)) {
    _series = chargeAnalysisChart.series[0]
  }
  return {
    ...chargeAnalysisChart,
    xAxis: { ...chargeAnalysisChart.xAxis, data: chargeAnalysises.value.map(item => item.dataTime) },
    series: [{ ..._series, data: chargeAnalysises.value.map(item => item.value) }]
  }
})
// 事件
const commEvent = {
  // 获取菜单信息
  getMenus: async () => {
    const { data } = await organTree()
    menus.value = commEvent.formatMenu(data)
    if (data && data.length > 0) {
      const _id: number = data[0].id
      menuId.value = _id
      openId.value = [_id]
    }
    commEvent.getDevice(true)
  },
  // 格式化菜单树
  formatMenu: (data: SystemApi.OrganTree[], pids?: number[]): any[] => {
    if (!data || data.length <= 0) return []
    return data.map(item => {
      let pidArr: number[] = []
      if (pids) {
        pidArr = [...pids, item.pid || 0]
      }
      return {
        id: item.id,
        text: item.organName,
        level: item.level,
        pid: item.pid,
        pidArr,
        children: commEvent.formatMenu(item.childrenTree || [], pidArr)
      }
    })
  },
  // 修改日期区间
  onDateRange: (value: string) => {
    const _date: any = {
      hour: dayjs().format("YYYY-MM-DD"),
      day: dayjs().format("YYYY-MM"),
      month: dayjs().format("YYYY")
    }
    searchValue.value.dataTime = _date[value]
  },
  // 菜单点击
  menuClick: (item: any) => {
    if (item.level === 1) {
      searchValue.value.factoryId = item.id
      searchValue.value.lineId = undefined
    } else if (item.level === 2) {
      searchValue.value.factoryId = item.pid
      searchValue.value.lineId = item.id
    } else {
      searchValue.value.factoryId = undefined
      searchValue.value.lineId = undefined
    }
    commEvent.getDevice(true)
  },
  // 获取设备信息
  getDevice: async (load?: boolean) => {
    const params: SystemArchive.DeviceListEnergyQuery = {
      lineId: searchValue.value.lineId,
      factoryId: searchValue.value.factoryId,
      energyType: searchValue.value.energyType
    }
    const { data } = await deviceListEnergy(params)
    devices.value = data
    if (data && data.length) {
      searchValue.value.deviceId = data[0].id
    } else {
      searchValue.value.deviceId = undefined
    }
    if (load) {
      commEvent.getStatData()
    }
  },
  // 重置功能
  onReset: () => {
    // 重置日期范围
    dateRange.value = "hour"

    // 重置搜索条件为初始值
    searchValue.value = {
      factoryId: undefined,
      lineId: undefined,
      dataTime: dayjs().format("YYYY-MM-DD"),
      deviceId: undefined,
      energyType: "electric"
    }

    // 清空数据显示
    chargeAnalysises.value = []
    desctrtionValue.value = {
      avgLoad: 0,
      loadRate: "0.00%"
    }

    // 重置菜单选择为第一个
    if (menus.value.length > 0) {
      const firstMenu = menus.value[0]
      menuId.value = firstMenu.id
      openId.value = [firstMenu.id]

      // 根据第一个菜单项设置厂区和产线信息
      if (firstMenu.level === 1) {
        searchValue.value.factoryId = firstMenu.id
        searchValue.value.lineId = undefined
      }
    }

    // 重新获取设备选项和统计数据
    commEvent.getDevice(true)
  },
  // 获取统计数据
  getStatData: async () => {
    if (!searchValue.value.deviceId) {
      desctrtionValue.value = { avgLoad: 0, loadRate: "0.00%" }
      chargeAnalysises.value = []
      return
    }
    const _date: any = {
      hour: { time: dayjs(searchValue.value.dataTime).format("YYYYMMDD"), suffix: "时" },
      day: { time: dayjs(searchValue.value.dataTime).format("YYYYMM"), suffix: "日" },
      month: { time: dayjs(searchValue.value.dataTime).format("YYYY"), suffix: "月" }
    }
    const _dataTime: string = _date[dateRange.value].time
    const _suffix: string = _date[dateRange.value].suffix
    const _timeType: number = dateValue[dateRange.value].timeType
    const params: SystemSpace.ElectricStatQuery = {
      deviceId: searchValue.value.deviceId,
      timeType: _timeType,
      dataTime: _dataTime
    }
    const { data } = await electricStat(params)
    if (!data) {
      desctrtionValue.value = { avgLoad: 0, loadRate: "0.00%" }
      chargeAnalysises.value = []
      return
    }
    const { avgLoad, loadList, loadRate } = data
    desctrtionValue.value = { avgLoad, loadRate }
    chargeAnalysises.value = loadList.map(item => ({
      value: item.value || 0,
      dataTime: item.dataTime.substring(item.dataTime.length - 2) + _suffix
    }))
  }
}
onMounted(() => {
  commEvent.getMenus()
})
</script>

<style lang="scss" scoped>
.energy-electricity-electriccharge {
  display: flex;
  width: 100%;
  height: calc(100vh - 100px);
  .card__title {
    position: relative;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    padding-left: 8px;
    font-size: 16px;
    font-weight: bold;
    &::before {
      position: absolute;
      left: 0;
      width: 3px;
      height: 75%;
      content: "";
      background-color: #1d4a9d;
      border-radius: 16px;
    }
  }
  .content__left {
    width: 200px;
    :deep(.el-card__body) {
      padding: 0;
    }
    height: 100%;
    overflow-y: auto;
    padding-right: 4px; /* 为滚动条留空间 */
    scroll-behavior: smooth;
    /* 滚动条宽度 */
    &::-webkit-scrollbar {
      width: 3px;
    }
  }
  .content__right {
    box-sizing: border-box;
    flex: 1;
    min-width: 0;
    padding: 0 10px;
    overflow-y: auto;
    .right-search {
      display: flex;
      align-items: center;
      width: 100%;
      .search__label {
        flex-shrink: 0;
        font-size: 13px;
      }
      .search__value {
        flex: 1;
      }
    }
    .right-chart {
      width: 100%;
      height: 400px;
    }
  }
}
</style>
